//
//  SARegisteredVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/1/26.
//

#import "SARegisteredVC.h"
#import "UILabel+NSMutableAttributedString.h"
#import "SAGetCheckCodeView.h"
#import "SAMerchantSendCodeAPI.h"
#import "SAMerchantRegisterAPI.h"
#import "HDWKWebVC.h"
#import "NSString+MD5.h"

@interface SARegisteredVC ()<HTTPAPIDelegate>

@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UILabel *userNameLab;
@property (nonatomic, strong) UITextField *userNameTf;
@property (nonatomic, strong) UIView *line1;
@property (nonatomic, strong) UILabel *shopNameLab;
@property (nonatomic, strong) UITextField *shopNameTf;
@property (nonatomic, strong) UIView *line2;
@property (nonatomic, strong) UILabel *shopAddressLab;
@property (nonatomic, strong) UITextField *shopAddressTf;
@property (nonatomic, strong) UIView *line3;
@property (nonatomic, strong) UILabel *iphoneLab;
@property (nonatomic, strong) UITextField *iphoneTf;
@property (nonatomic, strong) UIView *line4;
@property (nonatomic, strong) UILabel *verificationLab;
@property (nonatomic, strong) UITextField *verificationTf;
@property (nonatomic, strong) UIView *line5;
@property (nonatomic, strong) UILabel *passWordLab;
@property (nonatomic, strong) UITextField *passWordTf;
@property (nonatomic, strong) UIView *line6;

@property (nonatomic, strong) UIButton *registeredBtn;
@property (nonatomic, strong) UILabel *agreementLab;
@property (nonatomic, strong) UIButton *validationBtn;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;
@property (nonatomic, strong) SAMerchantSendCodeAPI *merchantSendCodeAPI;
@property (nonatomic, strong) SAMerchantRegisterAPI *merchantRegisterAPI;
@property (nonatomic, strong) UIButton *agreementBtn;

@end

@implementation SARegisteredVC

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.merchantSendCodeAPI == api) {
        [self startTime];
        [Prompt popPromptViewWithMsg:@"验证码已经发送" duration:2];
    }else if (self.merchantRegisterAPI == api) {
        [Prompt popPromptViewWithMsg:@"注册成功!" duration:2];
        [MobClick event:@"APP_register"];
        
        [self registerSuccessed];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
   
}

#pragma mark - event
-(void)obtainCodeTapEvent {
    [self.view endEditing:YES];
    if(trimString(self.iphoneTf.text).length == 0){
        [Prompt popPromptViewWithMsg:@"请输入手机号码" duration:2];
           return;
       }
       if(trimString(self.iphoneTf.text).length!=11){
           [Prompt popPromptViewWithMsg:@"手机号格式有误，请重新输入" duration:2];
           return;
       }
    WeakSelf
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    dict[@"mobile"] =  trimString(weakSelf.iphoneTf.text);
    [SANetManager requestWithType:SkyHttpRequestTypeGet urlString:SA_BASE_URL(@"/merchant/sendVerify") parameters:dict successBlock:^(id responseObject) {
        [Prompt popPromptViewWithMsg:@"验证码已经发送!" duration:2];
    } failureBlock:^(NSString *error) {

    }];
    
//    开启图形验证码
//    SAGetCheckCodeView *screenView = [SAGetCheckCodeView shareCornView];
//    [screenView loadStr:trimString(self.iphoneTf.text)];
//    [screenView showView:self];
//    screenView.selectedCodeBlock = ^(NSDictionary * _Nonnull dic) {
//        
//        if(trimString(weakSelf.iphoneTf.text).length == 0){
//            [Prompt popPromptViewWithMsg:@"请输入手机号码" duration:2];
//               return;
//           }
//           if(trimString(weakSelf.iphoneTf.text).length!=11){
//               [Prompt popPromptViewWithMsg:@"手机号格式有误，请重新输入" duration:2];
//               return;
//           }
//        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
//        dict[@"mobile"] =  trimString(weakSelf.iphoneTf.text);
//        dict[@"sessionId"] = dic[@"sessionId"];
//        dict[@"sig"] = dic[@"sig"];
//        dict[@"token"] = dic[@"token"];
//        dict[@"scene"] = dic[@"scene"];
//        [SANetManager requestWithType:SkyHttpRequestTypeGet urlString:SA_BASE_URL(URL_LOGIN_GET_CODE) parameters:dict successBlock:^(id responseObject) {
//            [Prompt popPromptViewWithMsg:@"验证码已经发送!" duration:2];
//        } failureBlock:^(NSString *error) {
// 
//        }];
//    };
}

-(void)startTime {
    self.validationBtn.userInteractionEnabled = NO;
    [self.validationBtn setTitle:[NSString stringWithFormat:@"剩余60秒"] forState:UIControlStateNormal];
    self.count = 60;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}

- (void)timerFired {
    if (self.count != 1) {
        self.count -= 1;
        [self.validationBtn setTitle:[NSString stringWithFormat:@"剩余%d秒", self.count] forState:UIControlStateNormal];
    } else {
        self.validationBtn.userInteractionEnabled = YES;
        [self.validationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)registeredBtnClick {
    if (trimString(self.userNameTf.text).length <=0) {
        [Prompt popPromptViewWithMsg:@"请输入姓名!" duration:2];
        return;
    }
    if (trimString(self.shopNameTf.text).length <=0) {
        [Prompt popPromptViewWithMsg:@"请输入店铺/企业名称!" duration:2];
        return;
    }
    if (trimString(self.shopAddressTf.text).length <=0) {
        [Prompt popPromptViewWithMsg:@"请输入店铺/企业地址!" duration:2];
        return;
    }
    if (trimString(self.iphoneTf.text).length <=0 ||trimString(self.iphoneTf.text).length !=11) {
        [Prompt popPromptViewWithMsg:@"请输入正确手机号!" duration:2];
        return;
    }
    if (trimString(self.verificationTf.text).length <=0 || trimString(self.verificationTf.text).length !=6) {
        [Prompt popPromptViewWithMsg:@"请输入正确手机号验证码!" duration:2];
        return;
    }
    if (trimString(self.passWordTf.text).length  <=0) {
        [Prompt popPromptViewWithMsg:@"请输入密码!" duration:2];
        return;
    }
      if(!(trimString(self.passWordTf.text).length >=6 &&trimString(self.passWordTf.text).length <=20)){
          [Prompt popPromptViewWithMsg:@"请输入6-20位数字，字母组合密码 !" duration:2];
               return;
           }
    
    self.merchantRegisterAPI.contactName = trimString(self.userNameTf.text);
    self.merchantRegisterAPI.merchantName = trimString(self.shopNameTf.text);
    self.merchantRegisterAPI.address = trimString(self.shopAddressTf.text);
    self.merchantRegisterAPI.contactMobile = trimString(self.iphoneTf.text);
    self.merchantRegisterAPI.code = trimString(self.verificationTf.text);
    self.merchantRegisterAPI.password = [NSString stringToMD5:trimString(self.passWordTf.text)];
    self.merchantRegisterAPI.registeredSource = @"iPhone";
    self.merchantRegisterAPI.marketSource = @"AppStore";
    self.merchantRegisterAPI.deviceTerminal = @"iOS";
    [self.merchantRegisterAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)clickedAgreementBtn {
    HDWKWebVC *webVC = [[HDWKWebVC alloc] initWithTitle:@"服务协议" AndUrl:@"http://ydtapi.kuaikuaifu.net/saas/ydt/ydtAgreement.html"];
    [self.navigationController pushViewController:webVC animated:YES];
}

-(void)registerSuccessed {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"message:@"基本信息注册完成,请开通支付后才能使用！" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self backToLastVC2];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"下一步" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self OpenPayment];
    }]];
}

//业务改变，需要返回上上个页面
-(void)backToLastVC2 {
    if (self.navigationController.viewControllers.count > 2) {
        UIViewController *vc = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 3];
        [self.navigationController popToViewController:vc animated:YES];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)OpenPayment {
    NSDictionary *dic = @{@"iphone" : trimString(self.iphoneTf.text), @"passWord" : trimString(self.passWordTf.text)};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"OpenPaymentLogin" object:dic];
}

-(void)dealloc
{
    HDLog(@"%@ 控制器已经被释放",NSStringFromClass([self class]));
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)initUI {
    [MobClick event:@"APP_register_page"];
    self.view.backgroundColor = kLineColor;
    
    UIImageView *topImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Login_top"]];
    topImageV.frame = SARectMake(0, 0, kBaseScreenWidth, 165 + DifferenceHeight);
    [self.view addSubview:topImageV];
    
    [self.view addSubview:self.backBtn];
    
    UILabel *tipLab = [[UILabel alloc] initWithFrame:SARectMake(24, 70 + DifferenceHeight, 200, 20)];
    tipLab.text = @"Hello!";
    tipLab.font = kBFont(18);
    tipLab.textColor = [UIColor whiteColor];
    tipLab.textAlignment = NSTextAlignmentLeft;
    [self.view  addSubview:tipLab];
    
    UILabel *tipLab2 = [[UILabel alloc] initWithFrame:SARectMake(24, 97 + DifferenceHeight, kBaseScreenWidth, 20)];
    tipLab2.text = @"欢迎注册衣点通";
    tipLab2.font = kBFont(18);
    tipLab2.textColor = [UIColor whiteColor];
    tipLab2.textAlignment = NSTextAlignmentLeft;
    [self.view  addSubview:tipLab2];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(15, 128 + DifferenceHeight, 345, 500)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.layer.cornerRadius = kScaleNum(5);
    whiteView.layer.masksToBounds = YES;
    [self.view addSubview:whiteView];
    
    [whiteView addSubview:self.userNameLab];
    [whiteView addSubview:self.userNameTf];
    [whiteView addSubview:self.line1];
    [whiteView addSubview:self.shopNameLab];
    [whiteView addSubview:self.shopNameTf];
    [whiteView addSubview:self.line2];
    [whiteView addSubview:self.shopAddressLab];
    [whiteView addSubview:self.shopAddressTf];
    [whiteView addSubview:self.line3];
    [whiteView addSubview:self.iphoneLab];
    [whiteView addSubview:self.iphoneTf];
    [whiteView addSubview:self.line4];
    [whiteView addSubview:self.verificationLab];
    [whiteView addSubview:self.verificationTf];
    [whiteView addSubview:self.line5];
    [whiteView addSubview:self.passWordLab];
    [whiteView addSubview:self.passWordTf];
    [whiteView addSubview:self.line6];
    
    [whiteView addSubview:self.registeredBtn];
    [self.view addSubview:self.agreementLab];
    [self.view addSubview:self.agreementBtn];
    [self.agreementLab setAttributedStringWithSubString:@"《衣点通用户服务协议》" color:kBuleColor];
}

- (UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setImage:[UIImage imageNamed:@"whiteAllow"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backToLastVC) forControlEvents:UIControlEventTouchUpInside];
        _backBtn.titleLabel.font = kFont(18);
        _backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        _backBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        _backBtn.frame = SARectMake(0, StatusHeight - 44, 60, 44);
    }
    return _backBtn;
}

-(UILabel *)userNameLab {
    if (!_userNameLab) {
        _userNameLab = [[UILabel alloc] initWithFrame:SARectMake(60, 20, 225, 16)];
        _userNameLab.text = @"姓名";
        _userNameLab.font = kFont(14);
        _userNameLab.textColor = kBlackColor;
    }
    return _userNameLab;
}

-(UITextField *)userNameTf {
    if (!_userNameTf) {
        _userNameTf = [[UITextField alloc] initWithFrame:SARectMake(60, 47, 225, 16)];
        _userNameTf.placeholder = @"请输入姓名(2-20个字符)";
        _userNameTf.font = kFont(14);
        _userNameTf.textColor = kBlackColor;
        _userNameTf.clearButtonMode = UITextFieldViewModeAlways;
    }
    return _userNameTf;
}

-(UIView *)line1 {
    if (!_line1) {
        _line1 = [[UIView alloc] initWithFrame:SARectMake(60, 71, 225, 1)];
        _line1.backgroundColor = kLineColor;
    }
    return _line1;
}

-(UILabel *)shopNameLab {
    if (!_shopNameLab) {
        _shopNameLab = [[UILabel alloc] initWithFrame:SARectMake(60, 91, 225, 16)];
        _shopNameLab.text = @"店铺/企业名称";
        _shopNameLab.font = kFont(14);
        _shopNameLab.textColor = [UIColor blackColor];
    }
    return _shopNameLab;
}

-(UITextField *)shopNameTf {
    if (!_shopNameTf) {
        _shopNameTf = [[UITextField alloc] initWithFrame:SARectMake(60, 118, 225, 16)];
        _shopNameTf.placeholder = @"请输入店铺或企业名称(2-24个字符)";
        _shopNameTf.font = kFont(14);
        _shopNameTf.textColor = kBlackColor;
        _shopNameTf.clearButtonMode = UITextFieldViewModeAlways;
    }
    return _shopNameTf;
}

-(UIView *)line2 {
    if (!_line2) {
        _line2 = [[UIView alloc] initWithFrame:SARectMake(60, 142, 225, 1)];
        _line2.backgroundColor = kLineColor;
    }
    return _line2;
}

-(UILabel *)shopAddressLab {
    if (!_shopAddressLab) {
        _shopAddressLab = [[UILabel alloc] initWithFrame:SARectMake(60, 162, 225, 16)];
        _shopAddressLab.text = @"店铺/企业地址";
        _shopAddressLab.font = kFont(14);
        _shopAddressLab.textColor = [UIColor blackColor];
    }
    return _shopAddressLab;
}

-(UITextField *)shopAddressTf {
    if (!_shopAddressTf) {
        _shopAddressTf = [[UITextField alloc] initWithFrame:SARectMake(60, 189, 225, 16)];
        _shopAddressTf.placeholder = @"请输入店铺或企业地址(5-40个字符)";
        _shopAddressTf.font = kFont(14);
        _shopAddressTf.textColor = kBlackColor;
        _shopAddressTf.clearButtonMode = UITextFieldViewModeAlways;
    }
    return _shopAddressTf;
}

-(UIView *)line3 {
    if (!_line3) {
        _line3 = [[UIView alloc] initWithFrame:SARectMake(60, 213, 225, 1)];
        _line3.backgroundColor = kLineColor;
    }
    return _line3;
}

-(UILabel *)iphoneLab {
    if (!_iphoneLab) {
        _iphoneLab = [[UILabel alloc] initWithFrame:SARectMake(60, 233, 225, 16)];
        _iphoneLab.text = @"手机号";
        _iphoneLab.font = kFont(14);
        _iphoneLab.textColor = [UIColor blackColor];
    }
    return _iphoneLab;
}

-(UITextField *)iphoneTf {
    if (!_iphoneTf) {
        _iphoneTf = [[UITextField alloc] initWithFrame:SARectMake(60, 260, 225, 16)];
        _iphoneTf.placeholder = @"请输入手机号";
        _iphoneTf.font = kFont(14);
        _iphoneTf.textColor = kBlackColor;
        _iphoneTf.clearButtonMode = UITextFieldViewModeAlways;
    }
    return _iphoneTf;
}

-(UIView *)line4 {
    if (!_line4) {
        _line4 = [[UIView alloc] initWithFrame:SARectMake(60, 284, 225, 1)];
        _line4.backgroundColor = kLineColor;
    }
    return _line4;
}

-(UILabel *)verificationLab {
    if (!_verificationLab) {
        _verificationLab = [[UILabel alloc] initWithFrame:SARectMake(60, 304, 225, 16)];
        _verificationLab.text = @"验证码";
        _verificationLab.font = kFont(14);
        _verificationLab.textColor = [UIColor blackColor];
    }
    return _verificationLab;
}

-(UITextField *)verificationTf {
    if (!_verificationTf) {
        _verificationTf = [[UITextField alloc] initWithFrame:SARectMake(60, 331, 225, 16)];
        _verificationTf.placeholder = @"请输入验证码";
        _verificationTf.font = kFont(14);
        _verificationTf.textColor = kBlackColor;
        _verificationTf.clearButtonMode = UITextFieldViewModeAlways;
        UIView *rightView = [[UIView alloc] initWithFrame:SARectMake(0, 0, 89, 35)];
        UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 10, 1, 17)];
        line.backgroundColor = kBuleColor;
        [rightView addSubview:line];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = SARectMake(1, 0, 88, 35);
        [btn setTitle:@"获取验证码" forState:UIControlStateNormal];
        btn.titleLabel.font = kFont(14);
        [btn setTitleColor:kBuleColor forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(obtainCodeTapEvent) forControlEvents:UIControlEventTouchUpInside];
        [rightView addSubview:btn];
        self.validationBtn = btn;
        _verificationTf.rightView = rightView;
        _verificationTf.rightViewMode = UITextFieldViewModeAlways;
    }
    return _verificationTf;
}

-(UIView *)line5 {
    if (!_line5) {
        _line5 = [[UIView alloc] initWithFrame:SARectMake(60, 355, 225, 1)];
        _line5.backgroundColor = kLineColor;
    }
    return _line5;
}

-(UILabel *)passWordLab {
    if (!_passWordLab) {
        _passWordLab = [[UILabel alloc] initWithFrame:SARectMake(60, 375, 225, 16)];
        _passWordLab.text = @"设置密码";
        _passWordLab.font = kFont(14);
        _passWordLab.textColor = [UIColor blackColor];
    }
    return _passWordLab;
}

-(UITextField *)passWordTf {
    if (!_passWordTf) {
        _passWordTf = [[UITextField alloc] initWithFrame:SARectMake(60, 402, 225, 16)];
        _passWordTf.backgroundColor = [UIColor whiteColor];
        _passWordTf.placeholder = @"请输入密码";
        _passWordTf.font = kFont(14);
        _passWordTf.textColor = kBlackColor;
        _passWordTf.clearButtonMode = UITextFieldViewModeAlways;
    }
    return _passWordTf;
}

-(UIView *)line6 {
    if (!_line6) {
        _line6 = [[UIView alloc] initWithFrame:SARectMake(60, 426, 225, 1)];
        _line6.backgroundColor = kLineColor;
    }
    return _line6;
}

-(UIButton *)registeredBtn {
    if (!_registeredBtn) {
        _registeredBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _registeredBtn.frame = SARectMake(60, 444, 225, 35);
        [_registeredBtn setTitle:@"立即注册" forState:UIControlStateNormal];
        _registeredBtn.titleLabel.font = kBFont(16);
        [_registeredBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_registeredBtn setBackgroundImage:[UIImage imageNamed:@"Login_btn_1"] forState:UIControlStateNormal];
        [_registeredBtn addTarget:self action:@selector(registeredBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registeredBtn;
}

-(UILabel *)agreementLab {
    if (!_agreementLab) {
        _agreementLab = [[UILabel alloc] initWithFrame:SARectMake(0, 638 + DifferenceHeight, kBaseScreenWidth, 12)];
        _agreementLab.text = @"注册即表示您已阅读并同意《衣点通用户服务协议》";
        _agreementLab.textAlignment = NSTextAlignmentCenter;
        _agreementLab.font = kFont(12);
        _agreementLab.textColor = kLightgGrayColor;
    }
    return _agreementLab;
}

-(UIButton *)agreementBtn {
    if (!_agreementBtn) {
        _agreementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _agreementBtn.frame = SARectMake(180, 633 + DifferenceHeight, 160, 22);
        [_agreementBtn addTarget:self action:@selector(clickedAgreementBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _agreementBtn;;
}

-(SAMerchantSendCodeAPI *)merchantSendCodeAPI {
    if (!_merchantSendCodeAPI) {
        _merchantSendCodeAPI = [SAMerchantSendCodeAPI apiWithDelegate:self];
    }
    return _merchantSendCodeAPI;
}

-(SAMerchantRegisterAPI *)merchantRegisterAPI {
    if (!_merchantRegisterAPI) {
        _merchantRegisterAPI = [SAMerchantRegisterAPI apiWithDelegate:self];
    }
    return _merchantRegisterAPI;
}

@end
